package com.feige.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.feige.pojo.Images;
import com.feige.result.AjaxResult;

import com.feige.service.ImagesService;
import com.feige.utils.FastdfsUtils;
import com.feige.utils.string.StringUtils;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 文件控制器
 * @author feige
 * @date 2020-10-27 23:24
 */
@Api(tags = "文件控制器")
@RestController
@RequestMapping("/fdfs")
public class UploadController {

    @Resource
    private FastdfsUtils fastdfsUtils;

    @Resource
    private ImagesService imagesService;


    @ApiOperation(value = "上传文件")
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file,String module) throws IOException {
        StorePath upload = fastdfsUtils.upload(file);
        AjaxResult ajaxResult;
        if (StringUtils.isNotNull(upload)){
            Images images = new Images();
            images.setModule(module);
            images.setOriginalFileName(file.getOriginalFilename());
            images.setPath(upload.getFullPath());
            imagesService.save(images);
            ajaxResult = AjaxResult.success();
            ajaxResult.put("path",upload.getFullPath());
        }else {
            ajaxResult = AjaxResult.error(500,"图片格式不合法");
        }
        return ajaxResult;
    }

    @ApiOperation(value = "删除文件")
    @ApiImplicitParam(name = "path",value = "文件路径如：group1/M00/00/00/rBEAAl6yXtiAarTtAAAQg9ci7ck503.png")
    @DeleteMapping("/delete")
    public AjaxResult delete(String path) {
        fastdfsUtils.delete(path);
        QueryWrapper<Images> wrapper = new QueryWrapper<>();
        wrapper.eq("path",path);
        imagesService.remove(wrapper);
        return AjaxResult.success();
    }
    @ApiOperation(value = "删除文件")
    @ApiImplicitParam(name = "paths",value = "文件路径列表")
    @DeleteMapping("/batch-delete")
    public AjaxResult batchDelete(@RequestBody List<String> paths) {
        for (String path : paths) {
            fastdfsUtils.delete(path);
        }
        QueryWrapper<Images> wrapper = new QueryWrapper<>();
        wrapper.in("path",paths);
        imagesService.remove(wrapper);
        return AjaxResult.success();
    }

    @ApiOperation(value = "下载文件")
    @GetMapping("/download")
    @ApiImplicitParam(name = "path",value = "文件路径如：group1/M00/00/00/rBEAAl6yXtiAarTtAAAQg9ci7ck503.png")
    public void download(String path, HttpServletResponse response) throws IOException {
        fastdfsUtils.download(path,response);
    }
}
